package com.bittech.facerecognition.web;

import com.bittech.facerecognition.config.FaceModel;
import com.bittech.facerecognition.model.Response;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;

/**
 * Author: secondriver
 * Created: 2019/5/28
 */
@WebServlet(urlPatterns = {"/detect"})
public class DetectFaceServlet extends ImageBaseServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        byte[] imageData = this.readImage(req, "faceImage");
        if (imageData == null) {
            this.responseJSON(resp, Response.ofFailed("", "人脸分析失败"));
        } else {
            FaceModel faceModel = this.faceAiClient.detect(imageData);
            this.responseJSON(resp, Response.ofOk(faceModel));
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String imageBase64 = req.getParameter("faceImage");
        byte[] imageData = Base64.getDecoder().decode(imageBase64);
        FaceModel faceModel = this.faceAiClient.detect(imageData);
        if (faceModel == null) {
            this.responseJSON(resp,Response.ofFailed("","人脸分析失败"));
        } else {
            this.responseJSON(resp, Response.ofOk(faceModel));
        }
    }
}